package com.itheima.reggie.web;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User_用户;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: cl
 * @Date: 2022/4/7 - 04 - 07
 * @Description:
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 发送手机验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User_用户 user, HttpSession session) {

        //获取前端传过来得手机号
        String phone = user.getPhone();
        //处理手机号空格问题
        if (phone != null) {
            phone = phone.trim();
        }
        if (StringUtils.isNotEmpty(phone)) {

            //生成随机的4位验证码
            String s = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("s = {}", s);

            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);

            //方式一：需要将生成的验证码和手机号保存到Session
            //session.setAttribute(phone, s);//手机号作为k验证码作为v  直接全验证
            //session.setAttribute("code", s);


            //方式二：需要将生成的验证码保存到Redis,设置过期时间
            redisTemplate.opsForValue().set(phone,s,5, TimeUnit.MINUTES);

            return R.success("手机验证码短信发送成功");
        }
        return R.success("短信发送失败！手机号有误！");
    }


    /**
     * 登录功能
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User_用户> login(@RequestBody Map map, HttpSession session) {

        log.info(map.toString());

        //获取手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //获取session中得手机号和验证码比对
        //String phone1 = session.getAttribute("phone").toString();
        //String code1 = session.getAttribute(phone).toString();
        //Object code1 = session.getAttribute(phone);

        //获取放在redis中缓存的验证码
        Object code1 = redisTemplate.opsForValue().get(phone);

        //比对
        if (code != null && code.equals(code1) ) {

            //如果能够比对成功，说明登录成功

            //判断手机号是不是新用户，如果不是需要保存再数据库
            User_用户 user = userService.getOne(
                    Wrappers.<User_用户>lambdaQuery()
                            .eq(User_用户::getPhone, phone)
            );

            //如果获取不到就是新用户   需要添加
            if (user == null) {
                user = new User_用户();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());

            //登录成功，删除redis缓存中验证码
            redisTemplate.delete(phone);

            return R.success(user);
        }
        return R.error("登录失败");
    }

    /**
     * 用户退出
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request) {
        //退出需要清理session中的永和Id
        request.getSession().removeAttribute("user");
        //或者直接销毁session
        request.getSession().invalidate();
        return R.success("退出成功！");
    }
}
